package com.cashmama.market.api.domain.vo.openapi.request;

import java.io.Serializable;

import com.fqgj.exception.common.ApplicationException;

import java.io.Serializable;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/10/15
 * Time: 10:29 上午
 */
public class PlatformSendData implements Serializable {

    private static final long serialVersionUID = 5367884945084476041L;

    private String method;

    private String merchantCode;

    private String sign;

    private String bizData;

    public PlatformSendData(String method, String merchantCode, String bizData) {
        this.method = method;
        this.merchantCode = merchantCode;
        this.bizData = bizData;
    }

    public PlatformSendData createSign(String key) {
        Map<String, String> data = new HashMap<>();
        data.put("method", this.method);
        data.put("merchantCode", this.merchantCode);
        data.put("bizData", this.bizData);
        try {
            this.sign = generateSignature(data, key);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ApplicationException("post sign create failed");
        }

        return this;
    }

    public String getMethod() {
        return method;
    }

    public String getSign() {
        return sign;
    }

    public String getBizData() {
        return bizData;
    }

    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
            {
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
            }
        }
        sb.append("key=").append(key);
        return MD5(sb.toString()).toUpperCase();

    }


    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

}
